package cs419.magnusmi.trackitcs;

import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;

public class ItemView extends ActionBarActivity {

    //text views for each field to be displayed
    TextView ID;
    TextView Name;
    TextView Serial;
    TextView Accessories;
    TextView SpecialFeatures;
    TextView OperatingSystem;
    TextView Pages;
    TextView OtherInfo;
    TextView CheckoutStatus;

    //asynchronous task to get data
    getItem iGetItem;

    //id to get data for
    String IDnum;
    Button edit;
    Button checkout;
    Button checkin;
    Button history;
    Button back;

    //session vars
    String user;
    String API;

    public String barData; //for barcode

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_view);

        //get number of item from intent
        Intent in = getIntent();
        IDnum = in.getStringExtra("id");

        //session vars
        user = in.getStringExtra("user");
        API = in.getStringExtra("API");

        //DEBUG
        //System.out.println(user);
        //System.out.println(API);
        //System.out.println(IDnum);

        //establish text views
        ID = (TextView) findViewById(R.id.textView);
        Name = (TextView) findViewById(R.id.textView2);
        Serial = (TextView) findViewById(R.id.textView3);
        Accessories = (TextView) findViewById(R.id.textView4);
        SpecialFeatures = (TextView) findViewById(R.id.textView5);
        OperatingSystem = (TextView) findViewById(R.id.textView6);
        Pages = (TextView) findViewById(R.id.textView7);
        OtherInfo = (TextView) findViewById(R.id.textView8);
        CheckoutStatus = (TextView) findViewById(R.id.textView9);

        //call asynchronous task to populate views
        setViews();

        edit = (Button) findViewById(R.id.editBtn);

        edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Launching edit activity
                Intent i = new Intent(getApplicationContext(), EditItem.class);
                i.putExtra("id", IDnum);
                i.putExtra("Name", Name.getText().toString());
                i.putExtra("Serial", Serial.getText().toString());
                i.putExtra("Accessories", Accessories.getText().toString());
                i.putExtra("SpecialFeatures", SpecialFeatures.getText().toString());
                i.putExtra("OperatingSystem", OperatingSystem.getText().toString());
                i.putExtra("Pages", Pages.getText().toString());
                i.putExtra("OtherInfo", OtherInfo.getText().toString());
                i.putExtra("CheckoutStatus", CheckoutStatus.getText().toString());

                //add session vars
                Utility.addToIntent(i, user, API);

                startActivity(i);
            }
        });

        checkout = (Button) findViewById(R.id.checkOutBtn);

        checkout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //check if already out
                if (!(CheckoutStatus.getText().toString().equals("in"))){
                    Context context = getApplicationContext();
                    int duration = Toast.LENGTH_LONG;
                    String message = "Item: " + ID.getText().toString() + " is not available for checkout";
                    Toast toast = Toast.makeText(context, message, duration);
                    toast.show();
                }

                //if not, perform checkout
                else {

                    //Pulls up the ZXing barcode scanner on the phone
                    try {
                        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                        startActivityForResult(intent, 0);
                    }

                    catch (ActivityNotFoundException anfe) {
                        Log.e("onCreate", "Scanner Not Found", anfe);
                    }

                }
            }
        });

        checkin = (Button) findViewById(R.id.checkInBtn);

        checkin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //check if already in
                if (!(CheckoutStatus.getText().toString().equals("out"))){
                    Context context = getApplicationContext();
                    int duration = Toast.LENGTH_LONG;
                    String message = "Item: " + ID.getText().toString() + " is already checked in";
                    Toast toast = Toast.makeText(context, message, duration);
                    toast.show();
                }

                //if not, perform checkin
                else {

                    //Pulls up the ZXing barcode scanner on the phone
                    try {
                        Intent intent = new Intent("com.google.zxing.client.android.SCAN");
                        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
                        startActivityForResult(intent, 1);
                    }

                    catch (ActivityNotFoundException anfe) {
                        Log.e("onCreate", "Scanner Not Found", anfe);
                    }

                }
            }
        });

        history = (Button) findViewById(R.id.historyBtn);

        history.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                Intent j = new Intent(getApplicationContext(), History.class);
                Utility.addToIntent(j, user, API);
                j.putExtra("id", IDnum);
                startActivity(j);
            }
        });

        back = (Button) findViewById(R.id.backBtn);

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(i, user, API);
                startActivity(i);

            }
        });
    }

    public void setViews(){
        //get detailed information for item
        iGetItem = new getItem();
        iGetItem.execute((Void) null);
    }

    /**
     * Handle variables captured from the ZXing barcode scanner and perform checkout/checkin depending on request flag
     * @param requestCode 0 for checkout, 1 for checkin
     * @param resultCode returned from scanner
     * @param intent scanner intent
     */
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 0 || requestCode == 1) {
            if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");

                barData = intent.getStringExtra("SCAN_RESULT");

                //just displays on screen what was scanned
                Toast toast = Toast.makeText(this, "Content:" + contents + " Format:" + format , Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400); //here it is (context, text, duration)
                toast.show();

                String newId = barData;

                boolean cancel = false;
                View focusView = null;

                //confirm input is not empty
                if (TextUtils.isEmpty(newId)){
                    cancel = true;
                    Context context = getApplicationContext();
                    CharSequence text = "There was no scan recorded. Scan was NULL";
                    int duration = Toast.LENGTH_SHORT;

                    Toast errToast = Toast.makeText(context, text, duration);
                    errToast.show();
                }

                //if not empty, confirm input is an integer
                if (!cancel) {
                    try {
                        Integer.parseInt(newId);
                    }
                    catch (NumberFormatException e){
                        cancel = true;
                        Context context = getApplicationContext();
                        CharSequence text = "The scanned barcode must represent only a number. Number exception.";
                        int duration = Toast.LENGTH_SHORT;

                        Toast errToast = Toast.makeText(context, text, duration);
                        errToast.show();
                    }
                }
                //if not empty and an integer, confirm that code matches item sought to be checked in/out
                if (!cancel){
                    if (Integer.parseInt(newId) != Integer.parseInt(IDnum)){
                        cancel = true;
                        Context context = getApplicationContext();
                        CharSequence text = "Scanned barcode does not match the item you have selected.\n" +
                                "Please try again";
                        int duration = Toast.LENGTH_SHORT;
                        Toast errToast = Toast.makeText(context, text, duration);
                        errToast.show();
                    }
                }

                if(!cancel){
                    if (requestCode == 0){
                        //Launching edit activity with session vars and item ID;
                        Intent j = new Intent(getApplicationContext(), checkout.class);
                        Utility.addToIntent(j, user, API);
                        j.putExtra("id", IDnum);
                        startActivity(j);
                    }
                    else if(requestCode == 1){
                        //Launching edit activity with session vars and item ID;
                        Intent j = new Intent(getApplicationContext(), checkin.class);
                        Utility.addToIntent(j, user, API);
                        j.putExtra("id", IDnum);
                        startActivity(j);
                    }
                }

            } else if (resultCode == RESULT_CANCELED) {
                // Handle cancel
                Toast toast = Toast.makeText(this, "Scan was Cancelled!", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP, 25, 400); //here it is (context, text, duration)
                toast.show();
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu (Menu menu)  {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.logout:
                Intent i = new Intent(getApplicationContext(), MainActivity.class);
                //clear stack to enforce logout (http://stackoverflow.com/questions/3007998/on-logout-clear-activity-history-stack-preventing-back-button-from-opening-l)
                i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
                        Intent.FLAG_ACTIVITY_CLEAR_TASK |
                        Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
                return true;
            case R.id.inventory_menu:
                Intent j = new Intent(getApplicationContext(), Inventory.class);
                Utility.addToIntent(j, user, API);
                startActivity(j);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to get item list
     * the user.
     */

    public class getItem extends AsyncTask<Void, Void, JSONObject> {


        @Override
        protected JSONObject doInBackground(Void... params) {

            //DEBUG System.out.println("getItem called");

            //url of PHP to get item data
            String getList = "http://web.engr.oregonstate.edu/~cohenad/cs419/index.php/getItem";

            //execute get request for list, using id retrieved from intent
            JSONParser jsonParser = new JSONParser();
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            parameters.add(new BasicNameValuePair("id", IDnum));

            //exectue http operation
            JSONObject json = jsonParser.makeHttpRequest(getList, "GET", parameters);

            //DEBUG System.out.println("getItem done");

            return json;
        }

        @Override
        protected void onPostExecute(JSONObject json) {

            try{
                //set text fields according to results
                ID.setText(json.getString("ItemID"));
                Name.setText(json.getString("Name"));
                Serial.setText(json.getString("Serial"));
                Accessories.setText(json.getString("Accessories"));
                SpecialFeatures.setText(json.getString("Special Features"));
                OperatingSystem.setText(json.getString("Operating System"));

                //special handler for pages to preserve numeric searchability at DB level
                String pages = json.getString("Pages");
                if (pages.equals("0")){
                    pages = "N/A";
                }
                Pages.setText(pages);
                OtherInfo.setText(json.getString("Other Information"));
                CheckoutStatus.setText(json.getString("Checked in or out"));
                //DEBUG System.out.println("getItem done2");
            }
            catch (JSONException e){
                Log.d("JSON", "JSON failed");
            }
        }
    }
}
